<?php
namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use app\models\LoginForm;
use app\models\Article;
use yii\data\Pagination;
use yii\web\UploadedFile;
use app\models\UploadForm;
use Yii\db\Connection;
use app\models\Album;
use app\models\SignupForm;
use app\models\User;
use app\models\Options;
use app\models\Comment;
use app\models\Xiong;
use app\models\Live;
use app\models\Comment_live;

/**
 * Admin controller
 */
class AdminController extends Controller
{
    /**
     * @inheritdoc
     */
    public $enableCsrfValidation = false;

     public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error','signup'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index','article','album','edit-art','del','user','setting','comment','live','edit-live','test','comment-live','upload','modify-art','modify-live'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }
    public function actions()
    {
        return [
        'upload' => [
            'class' => 'kucha\ueditor\UEditorAction',
            'config' => [
                "imageUrlPrefix"  => "",//图片访问路径前缀
                 /* 上传文件格式显示 */
                /* 列出指定目录下的图片 */
                  "imageUrlPrefix"          => "",
                /* 图片访问路径前缀 */
                "imagePathFormat"         => "/upload/image/{yyyy}{mm}{dd}{rand:3}",
                "imageManagerActionName"  => "listimage",
                /* 执行图片管理的action名称 */
                "imageManagerListPath"    => "/Xiong/web/upload/image/",
                /* 指定要列出图片的目录 */
                "imageManagerListSize"    => 20,
                /* 每次列出文件数量 */
                "imageManagerUrlPrefix"   => "",
                /* 图片访问路径前缀 */
                "imageManagerInsertAlign" => "none",
                /* 插入的图片浮动方式 */
                "imageManagerAllowFiles"  => [
                    ".png",
                    ".jpg",
                    ".jpeg",
                    ".gif",
                    ".bmp"
                ],
      
                  ], 
            ],
         'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
    ];
    }
     public $layout = 'mainchild';
        public function actionIndex()
        {
          // Yii::$app->view->params['customParam'] = 'aa';  调用actionIndex 时会传递一个值customParam到视图。
          // Yii::trace(Yii::$app->user->getId(), __METHOD__);
          // 传递选项nav_card的值
          $options = Options::find()->where(['option_name'=>'nav_card'])->one();
          $option1 = $options->option_value;
          $ariticle_num = count(Article::find()->all());
          $live_num = count(Live::find()->all());
          $artComm_num = count(Comment::find()->all());
          $liveComm_num = count(Live::find()->all());
          return $this->render('index',['option1'=>$option1,'art_num'=>$ariticle_num,'artComm_num'=>$artComm_num,'liveComm_num'=>$liveComm_num,'live_num'=>$live_num]);
        }
        public function actionArticle()
        {   
          $query = Article::find();
          $count = $query->count();
         $pagination = new Pagination(['totalCount' => $count,'pageSize' => '10']);
         $articles = $query->offset($pagination->offset)
          ->limit($pagination->limit)
          ->all();
          return $this->render('article',[
                   'articles' => $articles,
                   'pages' => $pagination,
             ]);        
          }

        public function actionEditArt()
        {  
             $article = new Article();

              if($article->load(\Yii::$app->request->post()) && $article->validate()){
                  $article->article_date = date("Y-m-d H:i:s",time());
                  $article->post_author_id =Yii::$app->user->getId();
                  $article->save();    
                  \Yii::$app->session->setFlash('success','文章添加成功');
                  return $this->refresh();
               }
            return $this->render('editArticle',['article'=>$article,'common'=>'笔记']);      
        }
        public function actionModifyArt()
        {  
            $request = Yii::$app->request;
            $id= $request->get('id');
             if($request->isPost)
              {                
                  $article = Article::getArticleById($id);
                  // 猜测 title和content 存入了article对象里，不能直接post获得，而load就ok
                  $article->load(\Yii::$app->request->post()) ;
                  if($article->validate())
                      $article->save();   
                  return $this->refresh();              
              }
            if($request->isGet)
              {
                $id= $request->get('id');
                $article = Article::getArticleById($id);
                return $this->render('modifyarticle',['article'=>$article,'common'=>'笔记']);
              }
             
                 
        }
        public function actionModifyLive()
        {  
            $request = Yii::$app->request;
             if($request->isPost)
              {
                 $id= $request->get('id');
                 $live = Live::getLiveById($id);
                  // 猜测 title和content 存入了article对象里，不能直接post获得，而load就ok
                  $live->load(\Yii::$app->request->post()) ;
                  if($live->validate())
                      $live->save();
                    return $this->refresh();
              }
            if($request->isGet)
              {
                $id= $request->get('id');
                $live = Live::getLiveById($id);
                return $this->render('modifylive',['live'=>$live,'common'=>'生活']);
              }
             
                 
        }

        public function actionComment()
        {
            // 有两个评论，因为公用一个comment页面。所以传递一个style来判断是哪个comment
         
          $query = Comment::find();
          $count = $query->count();
          $pagination = new Pagination(['totalCount' => $count,'pageSize' => '10']);
         $comment = $query->offset($pagination->offset)
          ->limit($pagination->limit)
          ->all();
          
          return $this->render('comment',[
                   'comment' => $comment,
                   'pages' => $pagination,
                   'comment_style'=>'art'
             ]);  

        }
        public function actionUser()
        {
                $u = new User();
                $user = $u->getUserInfor();
        	return $this->render('user',['user'=>$user]);
        }
        public function actionSetting()
        {
            // post接收要修改option和邮箱
            $request = Yii::$app->request;
             if(Yii::$app->request->isPost)
              {
                  // 获取user对象，并update邮箱
                   $id = Yii::$app->user->getId();
                   $object=User::findIdentity($id);
                   $object->email =  $request->post('email');
                   $object->save();
                  
                      // 按顺序给options update 
                      // addOptions($post,$num); $post为提交的数据，$num为options的数量
                   $o = new Options();
                   $o->addOptions($request->post(),4);
              }
            // $x,$user 获取数据并传递到view
            $os=  Options::getOptions();
            $id = Yii::$app->user->getId();
            $user=User::findIdentity($id);
            return $this->render('setting',['user'=>$user,'os'=>$os]);
        }
        public function actionAlbum()
      {
        // 获取image里的图片的路径并存入数据库 $dir = upload/image/   $file = *.jpg 之类
          $dir = 'upload/image';
          Yii::trace(is_dir($dir));
          if (is_dir($dir)) {   
              if ($dh = opendir($dir)) {   
                  while (($file = readdir($dh)) !== false) {   
                      if ($file!="." && $file!="..") {  
                        Yii::trace("aa");
                              Album::saveToDb($dir.'/'.$file);
                      }   
                  }   
                  closedir($dh);   
              }   
          }         
       $media =Album::find()->all();
        return $this->render('album', ['album'=>$media]);
    }
    public function actionDel()
    {
        if(Yii::$app->request->isPost)
          {
            $xi = new Xiong;
         $request = Yii::$app->request;
            if($request->post('fm')=="img")
              // fm为判断删除命令由哪个功能发出
            {               
                return $xi->rmImg($request->post('url'));
            }
            // 删除article
            else if($request->post('fm')=="art")
            {
                return $xi->rmArt($request->post('id'));                   
            }
            // 删除live
            else if($request->post('fm')=="live")
            {
               return $xi->rmLive($request->post('id'));                 
            }
            // 删除评论
             else if($request->post('fm')=="comment")
            {
              $t =$xi->rmComm($request->post('id'),$request->post('style'));
              if($t=="live_s")
                   return $this->redirect(['admin/comment-live','msg'=>'success']);
              else if($t=="art_s")
                   return $this->redirect(['admin/comment','msg'=>'success']);
            }
            // 批量删除article
            else if($request->post('fm')=="arts")
            {
              if($xi->rmBatchArt($request->post()))
                  return $this->redirect(['admin/article','msg'=>'success']);
              else
                  return $this->redirect(['admin/article','msg'=>'fail']); 
            }
            // 批量删除live
            else if($request->post('fm')=="lives")
            {
              if($xi->rmBatchLive($request->post()))
                  return $this->redirect(['admin/live','msg'=>'success']);
              else
                  return $this->redirect(['admin/live','msg'=>'fail']); 
            }           
          // 批量删除live-comment
          else if($request->post('fm')=="comm_lives")
            {
              if($xi->rmBatchLiveComm($request->post()))
                  return $this->redirect(['admin/comment-live','msg'=>'success']);
              else
                  return $this->redirect(['admin/comment-live','msg'=>'fail']); 
            }
             // 批量删除article-comment
            else if($request->post('fm')=="comms")
            {
               if($xi->rmBatchArtComm($request->post()))
                  return $this->redirect(['admin/comment','msg'=>'success']);
              else
                  return $this->redirect(['admin/comment','msg'=>'fail']); 
            }
          }
          else 
              return "fail";        
    }
     public function actionLogin()
    {   
        $this->layout = false;
        if (!Yii::$app->user->isGuest) {
           $this->redirect(array('/admin/index')); 
        }
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }
    public function actionSignup()
    {
        $this->layout = false;
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return "退出成功";
    }
    public function actionLive()
    {
        $query = Live::find();
          $count = $query->count();
         $pagination = new Pagination(['totalCount' => $count,'pageSize' => '10']);
         $lives = $query->offset($pagination->offset)
          ->limit($pagination->limit)
          ->all();
          return $this->render('live',[
                   'lives' => $lives,
                   'pages' => $pagination,
             ]);      
    }
    public function actionEditLive()
        {  
              $live = new Live();

              if($live->load(\Yii::$app->request->post()) && $live->validate()){
                  $live->create_date = date("Y-m-d H:i:s",time());
                  $live->post_author_id =Yii::$app->user->getId();
                  $live->save();    
                  \Yii::$app->session->setFlash('success','文章添加成功');
                  return $this->refresh();
               }
            return $this->render('editLive',['live'=>$live,'common'=>'日记']);     
        }
        public function actionCommentLive()
        {
          // 因为公用一个comment页面。所以传递一个style来判断是哪个comment
            // return $this->render('comment',['comment'=>Comment_live::getCommentToBackend(),'comment_style'=>'live']);  
            $query = Comment_live::find();
          $count = $query->count();
          $pagination = new Pagination(['totalCount' => $count,'pageSize' => '10']);
         $comment = $query->offset($pagination->offset)
          ->limit($pagination->limit)
          ->all();
          
          return $this->render('comment',[
                   'comment' => $comment,
                   'pages' => $pagination,
                   'comment_style'=>'live'
             ]);  
        }
}
